package services;

import domain.entities.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: nico
 * Date: 8/9/12
 * Time: 2:30 PM
 * To change this template use File | Settings | File Templates.
 */
@Service
public class SafetydocsService {

    private SafetydocsDAO dao;

    public SafetydocsService() {
    }

    @Autowired
    public SafetydocsService(SafetydocsDAO dao) {
        this.dao = dao;
    }

    public List<Safetydocs> findAll(){
        return dao.findAll();
    }

    public void save(Safetydocs docs){
        dao.save(docs);
    }

    public Safetydocs findById(Integer id){
        return dao.findById(id);
    }

    public void attachDirty (Safetydocs safetydocs){
        dao.attachDirty(safetydocs);
    }

    public List<Safetydocs> findByFiltros(Droga droga, Protocolo protocolo, Compromisopais pais, String docType,
                Date fecha, String email, Integer mailId){

        List<Droga> drogasProtocolo = new ArrayList<Droga>();
        if(protocolo != null)
            drogasProtocolo.addAll(protocolo.getDrogas());

        List<Safetydocs> safetydocs = this.dao.findByFiltros(droga, drogasProtocolo, fecha, mailId);

        Iterator<Safetydocs> itSafety = safetydocs.iterator();
        List<Safetydocs> aBorrar = new ArrayList<Safetydocs>();

        while(itSafety.hasNext()){
            Safetydocs actual = itSafety.next();

            if(pais != null){
                if(!actual.getCountries().contains(pais)){
                    aBorrar.add(actual);
                    continue;
                }
            }

            if(email != null && !email.equals("")){
                boolean existeMail = false;

                Iterator<SafetyRecipient> itMbms= actual.getRecipients().iterator();

                while(itMbms.hasNext()){
                    if(itMbms.next().getEmail().equals(email)){
                        existeMail = true;
                        break;
                    }
                }

                if(!existeMail){
                    aBorrar.add(actual);
                    continue;
                }
            }

            if(docType != null && !docType.equals("")){
                boolean existeType = false;

                Iterator<Envios> itEnvios = actual.getEnvioses().iterator();

                while(itEnvios.hasNext()){
                    if(itEnvios.next().getType().equals(docType)){
                        existeType = true;
                        break;
                    }
                }

                if(!existeType)
                    aBorrar.add(actual);
            }
        }
        safetydocs.removeAll(aBorrar);

        return safetydocs;
    }
}
